﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Web.Mvc;
using System.Text;
using System.EnterpriseServices;
using Webdiyer.WebControls.Mvc;
using YiYiTong.Rocket.Business;
using YiYiTong.Rocket.Entity;
using YiYiTong.Rocket.Model.Manager;
using YiYiTong.Rocket.Helper;

namespace YiYiTong.Rocket.ManageWeb.Controllers
{
    public class UserController : BaseController
    {
        #region 登录退出

        [NoVerify]
        public ActionResult Login()
        {
            //强制退出
            SignOut();
            return View();
        }

        [NoVerify]
        [HttpPost]
        public ActionResult Login(LoginReqModel reqLogin)
        {
            ResponseMsg resMsg = new ResponseMsg();
            string strOutPut = string.Empty;
            if (ModelState.IsValid)
            {
                //密码md5加密
                reqLogin.password = Utils.Md5Encrypt(reqLogin.password, Encoding.UTF8);

                if (SignIn(reqLogin, out strOutPut))
                {
                    string ReturnUrl = reqLogin.ReturnUrl;
                    //页面跳转
                    if (!string.IsNullOrEmpty(ReturnUrl))
                        resMsg.Body = ReturnUrl;
                    else
                        resMsg.Body = Url.Action("Index", "Home");
                }
                else
                {
                    //登录失败
                    resMsg.IsSuccess = false;
                    resMsg.Message = strOutPut;
                    return Json(resMsg, JsonRequestBehavior.AllowGet);
                }
            }
            else
            {
                resMsg.IsSuccess = false;
                resMsg.Message = strOutPut;
            }
            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }

        [Description("用户退出")]
        [NoVerify]
        public ActionResult LoginOut()
        {
            SignOut();
            return RedirectToAction("Login", "User");
        }
        #endregion

        #region 私有 登录退出

        //用户登入
        private bool SignIn(LoginReqModel reqLogin, out string strOutPut)
        {
            bool isLogin = false;
            string ip = Utils.GetClientIP();

            //登录
            long ret = UserBiz.Instance.UserLogin(reqLogin.loginName, reqLogin.password, ip, out strOutPut);
            if (ret > 0)
            {
                //登陆成功,记录cookies
                isLogin = true;
                reqLogin.uid = ret;
                string sessionKey = Guid.NewGuid().ToString("N");
                string lckey = ConfigHelper.AppSetting<string>("LoginCookieKey", "");
                Utils.SetCookie(lckey, sessionKey, "/", "", DateTime.Now.AddDays(1));

                UserInfo user = UserBiz.Instance.GetUserInfo(reqLogin.loginName);
                if (user != null && user.uid > 0)
                {
                    reqLogin.realName = user.realName;
                }
                else
                {
                    user = UserBiz.Instance.GetUserInfoByMobile(reqLogin.loginName);
                    reqLogin.realName = user.realName;
                    reqLogin.loginName = user.loginName;
                }
                //登陆model写入缓存中
                int timeout = ConfigHelper.AppSetting<int>("SessionTimeout", 60);
                DataCacheHelper.Set<LoginReqModel>(sessionKey, reqLogin, timeout * 60);

                //获取用户菜单,写入缓存中
                List<MenuInfo> menulist = UserBiz.Instance.GetUserMenuList(reqLogin.uid);
                DataCacheHelper.Set<List<MenuInfo>>(reqLogin.uid.ToString(), menulist, timeout * 60);

                //获取用户action功能，写入缓存
                List<ActionInfo> actionlist = UserBiz.Instance.GetUserActionList(reqLogin.uid);
                DataCacheHelper.Set<List<ActionInfo>>(reqLogin.uid.ToString() + reqLogin.loginName, actionlist, timeout * 60);
            }

            //记录登录日志
            UserBiz.Instance.WriteLoginLog(reqLogin.loginName, reqLogin.uid, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), ip, ConvertHelper.ConvertTo<int>(isLogin), strOutPut, "");
            return isLogin;
        }

        private void SignOut()
        {
            string lckey = ConfigHelper.AppSetting<string>("LoginCookieKey", "");
            try
            {
                string key = Utils.GetCookie(lckey);
                //移除缓存
                LoginReqModel user = DataCacheHelper.Get<LoginReqModel>(lckey);
                if (user != null && !string.IsNullOrEmpty(user.loginName))
                {
                    string uid = user.uid.ToString();
                    DataCacheHelper.Remove(uid);
                    DataCacheHelper.Remove(uid + user.loginName);
                }
                DataCacheHelper.Remove(key);
                Utils.SetCookie(lckey, "", "/", "", DateTime.Now);
                GC.Collect();
            }
            catch (Exception e)
            {
                LogHelper.Error("SignOut" + e.StackTrace);
            }
            finally
            {
                string key = Utils.GetCookie(lckey);
                DataCacheHelper.Remove(key);
                Utils.SetCookie(lckey, "", "/", "", DateTime.Now);
                GC.Collect();
            }
        }
        #endregion

        #region 用户列表
        [Description("查询用户列表")]
        [ViewPage]
        public ActionResult UserList(string loginName = "", int userStatus = -10, string begTime = "", string endTime = "", int pageIndex = 1, int pageSize = 10,int RoleID=-10)
        {
            var ds = UserBiz.Instance.GetPageList(loginName, userStatus, begTime, endTime, pageIndex, pageSize, RoleID);
            var allrows = ConvertHelper.ConvertTo<int>(ds.GetTable(0).Rows[0]["allrows"], 0);
            IList<UserModel> userlist = new ModelHandler<UserModel>().FillModel(ds, 1);
            PagedList<UserModel> pagedlist = null;
            if (userlist != null && userlist.Count != 0)
                pagedlist = new PagedList<UserModel>(userlist, pageIndex, pageSize, allrows);
            return View(pagedlist);
        }
        #endregion

        #region 添加/修改用户
        [Description("添加/修改用户")]
        [ViewPage]
        public ActionResult Register(long UID = 0)
        {
            UserInfo user = new UserInfo();
            if (UID != 0)
            {
                ViewBag.Title = "修改用户";
                user = UserBiz.Instance.GetUserInfoById(UID);
            }
            else
                ViewBag.Title = "添加用户";

            return View(user);
        }

        [Description("添加/修改用户")]
        [HttpPost]
        public ActionResult Register(UserInfo user)
        {
            ResponseMsg resMsg = new ResponseMsg();
            string strOutPut = string.Empty;
            int ret = 0;
            if (ModelState.IsValid)
            {
                if (user.uid == 0)
                {
                    //密码md5加密
                    user.password = Utils.Md5Encrypt(user.password, Encoding.UTF8);
                    //添加用户
                    ret = UserBiz.Instance.AddUserInfo(user.loginName, user.realName, user.password, user.userStatus, user.mobile, user.email, user.linkAddress, user.remark, 0, out strOutPut);
                }
                else
                {
                    //修改用户
                    ret = UserBiz.Instance.EditUserInfo(user.uid, user.realName, user.userStatus, user.mobile, user.email, user.linkAddress, user.remark, out strOutPut);
                }

                if (ret <= 0)
                {
                    resMsg.IsSuccess = false;
                    resMsg.Message = strOutPut;
                    return Json(resMsg, JsonRequestBehavior.AllowGet);
                }

                resMsg.Message = strOutPut;
                resMsg.Body = Url.Action("UserList", "User");
            }
            else
            {
                resMsg.IsSuccess = false;
                resMsg.Message = ModelState.Values.First().Errors[0].ErrorMessage;
            }
            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 删除用户
        [Description("删除用户")]
        [HttpPost]
        public ActionResult DelUser(int UID = 0)
        {
            int ret = 0;
            string strOutPut = string.Empty;
            ResponseMsg resMsg = new ResponseMsg();
            resMsg.Body = Url.Action("UserList", "User");
            if (UID != 0)
            {
                ret = UserBiz.Instance.DelUserInfo(UID, out strOutPut);
                if (ret <= 0)
                {
                    resMsg.IsSuccess = false;
                    resMsg.Message = strOutPut;
                    return Json(resMsg, JsonRequestBehavior.AllowGet);
                }
                resMsg.Message = strOutPut;
            }
            else
            {
                resMsg.IsSuccess = false;
                resMsg.Message = "用户不存在";
                return Json(resMsg, JsonRequestBehavior.AllowGet);
            }
            return Json(resMsg);
        }
        #endregion

        #region 密码修改
        [Description("重置密码")]
        [HttpPost]
        public ActionResult SetPwd(long UID)
        {
            ResponseMsg resMsg = new ResponseMsg();
            //生成6位随机密码
            string newpwd = Utils.GetRandomPwd(6);
            if (string.IsNullOrEmpty(newpwd))
            {
                resMsg.IsSuccess = false;
                resMsg.Message = "重置失败，随机生成新密码错误";
                return Json(resMsg, JsonRequestBehavior.AllowGet);
            }

            //开始重置密码
            string strOutPut = string.Empty;
            int ret = UserBiz.Instance.EditSelfPwd(UID, Utils.Md5Encrypt(newpwd, Encoding.UTF8), out strOutPut);
            if (ret <= 0)
            {
                resMsg.IsSuccess = false;
                resMsg.Message = strOutPut;
                return Json(resMsg, JsonRequestBehavior.AllowGet);
            }
            resMsg.Message = strOutPut;
            resMsg.Body = newpwd;
            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }

        [Description("修改密码")]
        [ViewPage]
        public ActionResult EditSelfPwd()
        {
            return View();
        }

        [Description("修改密码")]
        [NoVerify]
        [HttpPost]
        public ActionResult EditSelfPwd(EditPwdReqModel req)
        {
            ResponseMsg resMsg = new ResponseMsg();
            string strOutPut = string.Empty;
            int ret = 0;
            if (req.NewPwd != req.NewAgainPwd)
            {
                resMsg.IsSuccess = false;
                resMsg.Message = "新密码不一致";
                return Json(resMsg, JsonRequestBehavior.AllowGet);
            }
            else
            {
                //密码md5加密
                req.NewPwd = Utils.Md5Encrypt(req.NewPwd, Encoding.UTF8);
                var user = new CurrentUser();


                ret = UserBiz.Instance.EditSelfPwd(user.user.uid, req.NewPwd, out strOutPut);
                if (ret <= 0)
                {
                    resMsg.IsSuccess = false;
                    resMsg.Message = strOutPut;
                    return Json(resMsg, JsonRequestBehavior.AllowGet);
                }

                //修改密码成功，重新登录
                resMsg.Message = strOutPut;
                resMsg.Body = Url.Action("LoginOut", "User");
                return Json(resMsg, JsonRequestBehavior.AllowGet);
            }
        }
        #endregion

        #region 登录日志
        [Description("查询登录日志列表")]
        [ViewPage]
        public ActionResult LoginLogList(string loginName = "", string begTime = "", string endTime = "", int pageIndex = 1, int pageSize = 10)
        {
            var ds = UserBiz.Instance.GetLoginLogPageList(loginName, begTime, endTime, pageIndex, pageSize);
            var allrows = ConvertHelper.ConvertTo<int>(ds.GetTable(0).Rows[0]["allrows"], 0);
            IList<LoginLog> list = new ModelHandler<LoginLog>().FillModel(ds, 1);
            PagedList<LoginLog> pagedlist = null;
            if (list != null && list.Count != 0)
                pagedlist = new PagedList<LoginLog>(list, pageIndex, pageSize, allrows);
            return View(pagedlist);
        }
        #endregion

        #region 用户角色
        [Description("设置用户角色")]
        [ViewPage]
        public ActionResult SetRole(long UID, string LoginName)
        {
            UserModel user = new UserModel();
            if (UID != 0)
            {
                user.uid = UID;
                user.loginName = LoginName;

                DataTable dtUserRole = UserBiz.Instance.GetUserRoleList(UID);
                if (dtUserRole != null && dtUserRole.Rows.Count != 0)
                {
                    string str = string.Empty;
                    foreach (DataRow item in dtUserRole.Rows)
                    {
                        str += item["RoleID"].ToString() + ",";
                    }
                    str = str.Substring(0, str.Length - 1);
                    user.RoleIds = str;
                }
            }

            return View(user);
        }

        [Description("设置用户角色")]
        [HttpPost]
        public ActionResult SetRole(string UID, string roleIds)
        {
            ResponseMsg resMsg = new ResponseMsg();
            string strOutPut = string.Empty;
            int ret = 0;

            ret = UserBiz.Instance.SetUserRole(ConvertHelper.ConvertTo<long>(UID), roleIds);
            if (ret <= 0)
            {
                resMsg.IsSuccess = false;
                resMsg.Message = "设置角色失败";
                return Json(resMsg, JsonRequestBehavior.AllowGet);
            }
            else
            {
                resMsg.Message = "设置角色成功";
                resMsg.Body = Url.Action("UserList", "User");
            }
            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }

        [Description("获取角色角色")]
        [NoVerify]
        public ActionResult GetUserRoleNames(long UID)
        {
            string UserRoleNames = string.Empty;
            DataTable dt = UserBiz.Instance.GetUserRoleList(UID);
            if (dt != null && dt.Rows.Count != 0)
            {
                foreach (DataRow item in dt.Rows)
                {
                    int RoleID = ConvertHelper.ConvertTo<int>(item["RoleID"]);
                    RoleInfo role = RoleBiz.Instance.GetRoleInfoById(RoleID);
                    UserRoleNames += role.roleName + ",";
                }
                UserRoleNames = UserRoleNames.Substring(0, UserRoleNames.Length - 1);
            }
            return Content(UserRoleNames);
        }
        #endregion
    }
}